package org.hyjiacan.deadqq.client.window.event;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import org.hyjiacan.deadqq.client.window.LoginWindow;
import org.hyjiacan.deadqq.client.window.MainWindow;
import org.hyjiacan.deadqq.client.window.WindowManager;
import org.hyjiacan.deadqq.common.entity.User;

/**
 * 用户登录事件处理
 * 
 * @author hyjiacan
 * 
 */
public class Login implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		new Thread() {
			// 获取登录窗口实例
			LoginWindow lw = (LoginWindow) WindowManager.get(LoginWindow.class
					.getName());

			@Override
			public void run() {
				System.out.println("获取登录数据");
				User u;
				try {
					//获取用户输入的用户名和密码
					u = lw.getUser();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					return;
				}

				try {
					//连接到服务器
					Socket s = new Socket("127.0.0.1", 10453);
					System.out.println("已经成功连接到服务器，准备发送数据");
					ObjectOutputStream oos = new ObjectOutputStream(
							s.getOutputStream());

					System.out.println("开始发送登录请求");
					//将用户输入的数据发送给服务器
					oos.writeObject(u);
					oos.flush();
					System.out.println("数据发送完成");
					ObjectInputStream ois = new ObjectInputStream(
							s.getInputStream());
					//读取服务器的登录状态（true为登录成功，false为登录失败）
					boolean state = ois.readBoolean();
					System.out.println("得到登录状态" + state);
					if (state) {
						//读取用户的详细信息
						User ru = (User) ois.readObject();
						System.out.println("得到服务器返回数据：" + ru);
						//打开登录后的主界面
						new Thread(new MainWindow(ru)).start();
						//销毁登录窗口
						lw.dispose();
					}
				} catch (ClassNotFoundException | IOException e) {
					System.err.println("Server connect failed.");
					e.printStackTrace();
				}
			}
		}.start();
	}
}
